import  {router,addRoutes} from "@/router";
import {msg,showFullLoading,hideFullLoading} from '@/composables/util.js'
import {getinfo} from '@/api/manager.js'
import {mainStore} from '@/store/index'

let hasGetinfo=false //防止请求两次接口
router.beforeEach(async(to, from, next) => {
  
  const store = mainStore() 
  //显示loading
   showFullLoading()

    const token = localStorage.getItem('token');
    
    // 没有登录，强制跳转回登录页
    if (!token && to.path != "/login") {
      return next({ path: "/login" });
    }
  
    // 防止重复登录
    if (token && to.path == "/login") {
        msg("請勿重複登錄", "error");
      return next({ path: from.path ? from.path : "/" });
    }

    let hasNewRoutes=false
  if (token && !hasGetinfo ) {
    let info= await store.admin()
    hasNewRoutes = addRoutes(info.menu)
    hasGetinfo=true
  }

  // 设置页面标题
    let title = (to.meta.title ? to.meta.title : "");
    document.title = title;
    hasNewRoutes ? next(to.fullPath) : next()
 
  });

  // 全局后置守卫
router.afterEach((to, from) => hideFullLoading());